<template>
  <view class="address-edit-page">
    <!-- 页面头部 -->
    
    <!-- 表单内容 -->
    <view class="form-content">
      <view class="form-item">
        <text class="form-label">收货人</text>
        <input v-model="form.name" placeholder="收货人姓名" class="form-input" />
      </view>
      
      <view class="form-item">
        <text class="form-label">手机号</text>
        <input v-model="form.phone" placeholder="收货人手机号" class="form-input" />
      </view>
      
      <view class="form-item">
        <text class="form-label">地区</text>
        <view class="region-picker" @click="showRegionPicker">
          <text v-if="form.province && form.city && form.district">{{ form.province }} {{ form.city }} {{ form.district }}</text>
          <text v-else class="placeholder">请选择地区</text>
          <text class="arrow">></text>
        </view>
      </view>
      
      <view class="form-item">
        <text class="form-label">详细地址</text>
        <view class="detail-address">
          <input v-model="form.detail" placeholder="如街道、门牌号、小区、乡镇、村等" class="form-input" />
          <view class="location-btn">
            <text class="location-icon">📍</text>
            <text class="location-text">定位</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 保存按钮 -->
    <button class="save-btn" @click="submitForm">保存</button>
    
    <!-- 地区选择器弹窗 -->
    <view class="region-picker-modal" v-if="showRegionPickerModal" @click="closeRegionPicker">
      <view class="region-picker-content" @click.stop>
        <view class="picker-header">
          <text class="cancel-btn" @click="closeRegionPicker">取消</text>
          <text class="confirm-btn" @click="confirmRegion">确认</text>
        </view>
        <view class="picker-columns">
          <!-- 省份列表 -->
          <view class="picker-column">
            <view class="column-title">选择省份</view>
            <scroll-view class="column-content" scroll-y>
              <view 
                class="picker-item" 
                v-for="(item, index) in provinceList" 
                :key="index"
                :class="{ selected: provinceIndex === index }"
                @click="selectProvince(index, item)"
              >
                {{ item.districtName }}
              </view>
            </scroll-view>
          </view>
          
          <!-- 城市列表 -->
          <view class="picker-column" v-if="cityList.length > 0">
            <view class="column-title">选择城市</view>
            <scroll-view class="column-content" scroll-y>
              <view 
                class="picker-item" 
                v-for="(item, index) in cityList" 
                :key="index"
                :class="{ selected: cityIndex === index }"
                @click="selectCity(index, item)"
              >
                {{ item.districtName }}
              </view>
            </scroll-view>
          </view>
          
          <!-- 区县列表 -->
          <view class="picker-column" v-if="districtList.length > 0">
            <view class="column-title">选择区县</view>
            <scroll-view class="column-content" scroll-y>
              <view 
                class="picker-item" 
                v-for="(item, index) in districtList" 
                :key="index"
                :class="{ selected: districtIndex === index }"
                @click="selectDistrict(index, item)"
              >
                {{ item.districtName }}
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { addAddress, editAddress, getDistricts } from '@/api/address'
export default {
  data() {
    return {
      form: {
        id: null,
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: '0'
      },
      // 省市区数据
      provinceList: [],
      cityList: [],
      districtList: [],
      // 选中的索引
      provinceIndex: 0,
      cityIndex: 0,
      districtIndex: 0,
      // 选中的ID
      selectedProvinceId: null,
      selectedCityId: null,
      selectedDistrictId: null,
      // 弹窗控制
      showRegionPickerModal: false
    }
  },
  onLoad(options) {
    // 只加载省份数据（第一级）
    this.loadProvinces();
    
    if (options && options.id) {
      const data = JSON.parse(decodeURIComponent(options.data));
      this.form = { ...data, isDefault: data.isDefault ? '1' : '0' };
      if (options.id !== 'undefined' && options.id !== undefined) {
        this.form.id = Number(options.id);
      } else {
        delete this.form.id;
      }
    }
  },
  methods: {
    // 加载省份数据
    async loadProvinces() {
      try {
        console.log('开始加载省份数据，pid=1');
        const res = await getDistricts(1); // 第一级默认pid为1
        console.log('省份数据返回:', res);
        if (res.code === 200 && res.data) {
          this.provinceList = res.data;
          console.log('省份数据设置成功，数量:', this.provinceList.length);
        } else {
          console.log('省份数据返回异常:', res);
        }
      } catch (error) {
        console.error('加载省份数据失败:', error);
        uni.showToast({ title: '加载省份数据失败', icon: 'none' });
      }
    },
    
    // 加载城市数据
    async loadCities(provinceId) {
      try {
        console.log('加载城市数据，pid=', provinceId);
        const res = await getDistricts(provinceId);
        console.log('城市数据返回:', res);
        if (res.code === 200 && res.data) {
          this.cityList = res.data;
        }
      } catch (error) {
        console.error('加载城市数据失败:', error);
        uni.showToast({ title: '加载城市数据失败', icon: 'none' });
      }
    },
    
    // 加载区县数据
    async loadDistricts(cityId) {
      try {
        console.log('加载区县数据，pid=', cityId);
        const res = await getDistricts(cityId);
        console.log('区县数据返回:', res);
        if (res.code === 200 && res.data) {
          this.districtList = res.data;
        }
      } catch (error) {
        console.error('加载区县数据失败:', error);
        uni.showToast({ title: '加载区县数据失败', icon: 'none' });
      }
    },
    
    // 省份选择事件（点击）
    selectProvince(index, province) {
      this.provinceIndex = index;
      this.selectedProvinceId = province.id;
      this.form.province = province.districtName;
      
      // 清空城市和区县
      this.form.city = '';
      this.form.district = '';
      this.cityList = [];
      this.districtList = [];
      this.cityIndex = 0;
      this.districtIndex = 0;
      
      // 选择省份后立即加载城市数据（第二级）
      console.log('选择省份:', province.districtName, 'ID:', province.id);
      this.loadCities(province.id);
    },
    
    // 城市选择事件（点击）
    selectCity(index, city) {
      this.cityIndex = index;
      this.selectedCityId = city.id;
      this.form.city = city.districtName;
      
      // 清空区县
      this.form.district = '';
      this.districtList = [];
      this.districtIndex = 0;
      
      // 选择城市后立即加载区县数据（第三级）
      console.log('选择城市:', city.districtName, 'ID:', city.id);
      this.loadDistricts(city.id);
    },
    
    // 区县选择事件（点击）
    selectDistrict(index, district) {
      this.districtIndex = index;
      this.selectedDistrictId = district.id;
      this.form.district = district.districtName;
    },
    
    // 显示地区选择器
    showRegionPicker() {
      console.log('点击地区选择器');
      console.log('省份数据:', this.provinceList);
      
      // 确保省份数据已加载
      if (this.provinceList.length === 0) {
        console.log('省份数据为空，重新加载');
        this.loadProvinces().then(() => {
          this.showRegionPickerModal = true;
        });
      } else {
        this.showRegionPickerModal = true;
      }
    },
    
    // 关闭地区选择器
    closeRegionPicker() {
      this.showRegionPickerModal = false;
    },
    
    // 确认地区选择
    confirmRegion() {
      this.closeRegionPicker();
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    onDefaultChange(e) {
      this.form.isDefault = e.detail.value.length > 0 ? '1' : '0';
    },
    submitForm() {
      const userId = this.$store.state.user.id || uni.getStorageSync('userId');
      if (!userId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      const data = { ...this.form, userId, isDefault: this.form.isDefault === '1' ? 1 : 0 };
      if (data.id === undefined || data.id === 'undefined') {
        delete data.id;
      }
      const api = data.id ? editAddress : addAddress;
      api(data).then(res => {
        if (res.code === 200) {
          uni.showToast({ title: '保存成功', icon: 'success' });
          setTimeout(() => {
            // 通知上级页面刷新
            const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
            if (eventChannel) {
              eventChannel.emit('addressChanged');
            }
            uni.navigateBack();
          }, 600);
        } else {
          uni.showToast({ title: res.msg || '保存失败', icon: 'none' });
        }
      });
    }
  }
}
</script>

<style scoped>
.address-edit-page {
  background: #f5f5f5;
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  background: #fff;
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.back-btn {
  font-size: 40rpx;
  color: #333;
  margin-right: 20rpx;
  cursor: pointer;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
}

.form-content {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  padding-bottom: 20rpx;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.form-input {
  width: 100%;
  height: 60rpx;
  border: none;
  font-size: 28rpx;
  color: #333;
  background: transparent;
}

.form-input::placeholder {
  color: #999;
}

.region-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60rpx;
  cursor: pointer;
}

.region-picker .placeholder {
  color: #999;
}

.region-picker .arrow {
  color: #999;
  font-size: 24rpx;
}

.detail-address {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.detail-address .form-input {
  flex: 1;
}

.location-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5rpx;
  cursor: pointer;
}

.location-icon {
  font-size: 32rpx;
}

.location-text {
  font-size: 20rpx;
  color: #ff4d4f;
}

.save-btn {
  width: 90%;
  height: 80rpx;
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
  margin: 30rpx auto;
  display: block;
}

/* 地区选择器样式 */
.region-picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1002;
  display: flex;
  align-items: flex-end;
}

.region-picker-content {
  width: 100%;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 70%;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.cancel-btn {
  font-size: 28rpx;
  color: #666;
  cursor: pointer;
}

.confirm-btn {
  font-size: 28rpx;
  color: #07c160;
  font-weight: bold;
  cursor: pointer;
}

.picker-columns {
  display: flex;
  height: 400rpx;
}

.picker-column {
  flex: 1;
  height: 100%;
  border-right: 1rpx solid #f0f0f0;
}

.picker-column:last-child {
  border-right: none;
}

.column-title {
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 24rpx;
  color: #999;
  background: #f8f8f8;
  border-bottom: 1rpx solid #f0f0f0;
}

.column-content {
  height: calc(100% - 60rpx);
}

.picker-item {
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  cursor: pointer;
  transition: all 0.2s;
}

.picker-item:hover {
  background: #f5f5f5;
}

.picker-item.selected {
  color: #07c160;
  font-weight: bold;
  background: #e8f5e8;
}
</style> 